package database;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import mockup.UserMockup;

import server.database.ConnectionDatabase;

public class LoginDB {
	
	private Statement st;
	
	public LoginDB () {
		try {
			st = ConnectionDatabase.getConnection().createStatement();			
		} catch (Exception e) {
			System.err.println("AppoitmentDB::Constructor:Exception: " + e.getMessage());
		}
	}
	
	public UserMockup getUser(String username, String pass) {
		int userId = validate(username, pass);
		if(userId > 0) {
			return DataHandler.user.get(userId);
		}
		return null;
	}

	public int validate(String username, String pass) {
		//TODO: should have a check that the name and pass not a query or crack line
		String query = "select * from " + ConnectionDatabase.getNameDB() + ".setting " +
		"where username = '" + username + "' and password = '" + pass + "'";

		int count = 0;
		int id = -1;

		ResultSet rs = ConnectionDatabase.get(query, st);
		try {
			while (rs.next()) {
				id = rs.getInt("user_id");
				count++;
			}

		} catch (SQLException e ) {
			System.err.println("LoginDB::validate:SQLException: " + e.getMessage());
		}

		if(count == 1) {
			return id;
		}
		return -1;
	}
}
